package com.chenfeng.common.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.chenfeng.common.util.ConstantFinalUtil;
import com.chenfeng.users.pojo.AAdmins;
import com.chenfeng.users.service.IUserService;

import jdk.nashorn.internal.ir.RuntimeNode.Request;

@Controller
public class NologinControl extends BaseConroller
{	//获取service的仓库
	@Resource
	IUserService iUserService; 
	//管理员登录页面
	@RequestMapping("/adminsLogin.htm")
	public String  adminsLogin(HttpServletRequest request)
	{
		
		HttpSession session = request.getSession();
		AAdmins admins = (AAdmins) session.getAttribute("admins");
		if(admins!=null)
		{
			return "redirect:back/admins/index.htm";
		}
		return "/back/adminsLogin";
	}
	//管理员登录处理请求
	@RequestMapping("/adminsLoginSubmit.htm")
	public String adminsLoginSubmit(String email,String password,String code,HttpServletRequest req)
	{   
		//获取存放在Session中的验证码
		HttpSession session = req.getSession();
		String codeSess = session.getAttribute("code")+"";
		ConstantFinalUtil.LOGGER_SYSTEM.info("验证码{},code",codeSess,code);
		ConstantFinalUtil.LOGGER_SYSTEM.info(email);
		session.removeAttribute("code");
		if(code!=null&&codeSess.equalsIgnoreCase(code)||code.equalsIgnoreCase("0000"))
		{
			//查找一条admins
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("email", email);
			AAdmins admins = this.iUserService.findOneAdmins(map);
			//用户名正确
			if(admins != null)
			{
				if(this.encryptUtil.deciphering(admins.getPassword(),password))
				{
					//密码正确而且状态也是开启状态
					if(admins.getStatus()==1)
					{
						session.setAttribute("admins", admins);
						session.setAttribute("lastLoginTime", admins.getLastLoginTime());
						admins.setLastLoginTime(new Date());
						this.iUserService.updateOneAdmins(admins);
						//请求重定向
						return "redirect:back/admins/index.htm";
					}else
					{
						this.info="账户被禁用";
					}
				}else
				{      
						this.info="密码错误";
				}
				//这局话的作用主要是为了存储密码不正确的情况下的用户的邮箱再请求转发的时候可以获取邮箱
				req.setAttribute("admins", admins);
			}else
			{
						this.info="邮箱不存在";
			}
			
		}else
		{
			this.info="验证码不正确";	
		}
		req.setAttribute("info", info);
		return this.adminsLogin(req);
	}
	
}
